using UnityEngine;
using System.Collections;

public class EnemyMeleeBehaviour : CharacterBehaviour
{
	public bool enable = true;
	
	[SerializeField]
	private Transform point1 = null, point2 = null;
	
	[SerializeField]
	private DetectorCollider detector = null, enemyDetector = null;
	
	private Vector2 normalizedDirection = Vector2.zero;
	
	private Vector3 pointToGo = Vector3.zero;
	
	private float timeToAttack = 0f;
	
	private bool canMove = true;
	
	protected override void Awake()
	{
		base.Awake();
		
		_transform = transform;
		
		point1.parent = null; point2.parent = null;
		
		if(enable)
		{
			StartCoroutine(WaitToStartMove());
		}
	}
	
	protected override void Update() 
	{
		if(enable && !onHit && hp > 0 && ManagerGame.enableAction)
		{
			if(enemyDetector.IsFree)
			{
				if(canMove)
				{
					timeToAttack = 0;
					
					if(!base.footDetector.IsFree && normalizedDirection.y < 0)
					{
						velocity = new Vector2(velocity.x, 0);
						normalizedDirection = new Vector2(normalizedDirection.x, 0);
					}
					
					base.TryMove(normalizedDirection);
				}
				else
				{
					base.velocity = Vector2.zero;
				}
			}
			else
			{
				base.velocity = Vector2.zero;
				
				timeToAttack -= Time.deltaTime;
				
				if(timeToAttack <= 0)
				{
					base.Melee();
					timeToAttack = 0.5f;
				}
			}
		}
		
		base.Update();
	}
	
	private IEnumerator WaitToStartMove()
	{
		yield return new WaitForSeconds(1f);
		
		canMove = false;
		if(enemyDetector.IsFree)
		{
			base.animationUV.Play("walk");
		}
		
		StartCoroutine(WaitToChooseGoal());
	}
	
	private IEnumerator WaitToChooseGoal()
	{
		yield return new WaitForSeconds(1f);
		
		if(enemyDetector.IsFree)
		{
			if(detector.IsFree)
			{
				base.animationUV.Play("walk");
				if(pointToGo.Equals(point1.position))
				{
					pointToGo = point2.position;
				}
				else
				{
					pointToGo = point1.position;
				}
			}
			else
			{
				base.animationUV.Play("meleePrep");
				
				pointToGo = detector.GetAnyTarget.transform.position;
			}
			
			canMove = true;
			
			normalizedDirection = new Vector2(pointToGo.x - _transform.position.x,
											  pointToGo.y - _transform.position.y);
			
			normalizedDirection.Normalize();
		}
		
		StartCoroutine(WaitToStartMove());
	}
}
